package cc.smarnet.caihou.phone.deliver;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import cc.smarnet.caihou.IPConfig;
import cc.smarnet.caihou.LoginActivity;
import cc.smarnet.caihou.R;

import cc.smarnet.caihou.phone.deliver.DeliverActivity;
import cc.smarnet.caihou.util.DateUtil;
import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 新增出库的activity
 */
public class DeliverAddActivity extends AppCompatActivity {
    private ImageButton imageButton;
    private EditText stockOutUserEditText;//出库人;
    private EditText carDerverEditText;//司机;
    private EditText carNoEditText;//车牌;
    private EditText stockInTimeEditText;//出库时间;
    private EditText remarksEditText;//备注;
    private Button confirmButton;
    private ProgressBar progressBar;


    private String token;

    private String carDerver; // 司机
    private String carNo; // 车牌
    private String number; // 出库数量
    private String stockInTime; // 出库时间
    private String stockOutUser; // 出库人
    private String remarks; // 备注

    int mYear, mMonth, mDay;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deliver_add);

        getSupportActionBar().hide();//隐藏标题栏

        initViews();
        progressBar.setVisibility(View.GONE);
        getToken();

        stockInTime=DateUtil.currentDate();
        stockInTimeEditText.setText(stockInTime);// 设置默认的出库时间

        getDate();// 获取当前的日期
        // 选择分拣日期的监听
        stockInTimeEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(DeliverAddActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int month, int day) {
                                mYear = year;
                                mMonth = month;
                                mDay = day;
                                String transMonth = String.format("%02d", mMonth + 1);// 如果月份小于10的话进行补0
                                String transDay = String.format("%02d", mDay);// 如果日小于10的话进行补0
                                stockInTime = mYear + "-" + transMonth + "-" + transDay;
                                stockInTimeEditText.setText(stockInTime);
                            }
                        }, mYear, mMonth, mDay);
                datePickerDialog.show();
            }
        });
        // 点击确认按钮的监听
        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取出库人
                if (stockOutUserEditText.getText().toString().equals("")){
                    AlertDialog alertDialog = new AlertDialog.Builder(DeliverAddActivity.this).create();
                    alertDialog.setMessage("请输入出库人！");
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                    return;
                }else {
                    stockOutUser=stockOutUserEditText.getText().toString();
                }

                //获取司机
                if (carDerverEditText.getText().toString().equals("")){
                    AlertDialog alertDialog = new AlertDialog.Builder(DeliverAddActivity.this).create();
                    alertDialog.setMessage("请输入司机名称！");
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                    return;
                }else {
                    carDerver=carDerverEditText.getText().toString();
                }

                //获取车牌
                if (carNoEditText.getText().toString().equals("")){
                    AlertDialog alertDialog = new AlertDialog.Builder(DeliverAddActivity.this).create();
                    alertDialog.setMessage("请输入车牌号！");
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                    return;
                }else {
                    carNo=carNoEditText.getText().toString();
                }

                // 获取备注
                if (!remarksEditText.getText().toString().equals("")){
                    remarks=remarksEditText.getText().toString();
                }
                // 新增入库信息
                addDeliver();
            }
        });
        // 点击返回按钮的监听
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void initViews() {
        imageButton = findViewById(R.id.deliver_add_return);
        stockOutUserEditText = findViewById(R.id.deliver_add_stockOutUser_editText);
        carDerverEditText = findViewById(R.id.deliver_add_carDerver_editText);
        carNoEditText = findViewById(R.id.deliver_add_carNo_editText);
        stockInTimeEditText = findViewById(R.id.deliver_add_stockInTime_editText);
        remarksEditText = findViewById(R.id.deliver_add_remarks_editText);
        confirmButton = findViewById(R.id.deliver_confirm_add_button);
        progressBar = findViewById(R.id.deliver_add_progressBar);
    }

    public void getToken() {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        token = sp.getString("token", null);
    }


    // 新增毛产品信息
    public void addDeliver() {
        confirmButton.setClickable(false);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("carDerver", carDerver);//司机
        map.put("carNo", carNo);//车牌
        map.put("number", number);//出库数量
        map.put("stockInTime", stockInTime);//出库时间
        map.put("stockOutUser", stockOutUser);//出库人
        map.put("remarks", remarks);//备注

        String requestJsonString = JSON.toJSONString(map);
        String url = IPConfig.baseUrl + "/flower/flowerOutorder/add";
        OkHttpUtils
                .postString()
                .addHeader("X-Access-Token", token)
                .url(url)
                .content(requestJsonString)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        confirmButton.setClickable(true);
                        Toast.makeText(DeliverAddActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(DeliverAddActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        confirmButton.setClickable(true);
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            AlertDialog alertDialog = new AlertDialog.Builder(DeliverAddActivity.this).create();
                            alertDialog.setMessage("出库信息新增成功");
                            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(DeliverAddActivity.this, DeliverActivity.class);
                                    startActivity(intent);
                                }
                            });
                            alertDialog.setCanceledOnTouchOutside(false);
                            alertDialog.show();
                        }
                    }
                });
    }

    // 获取当前日期
    public void getDate() {
        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
    }
}